import { Component, ElementRef, HostBinding, OnDestroy } from '@angular/core';
import { IHeaderParams } from '@ag-grid-enterprise/all-modules';
import { IHeaderAngularComp } from '@ag-grid-community/angular';
import { ExpressionService } from '@core/services/expression/ExpressionService';
import { deepClone, getO } from '../../../utils/utils';
import { ApesInputFormComponent } from '@shared/apes-input-form';
import { Events } from '@core/services/events/Events';
import { SearchService } from '@core/services/search.service';

interface MyParams extends IHeaderParams {
  menuIcon: string;
}

@Component({
  template: `
    <div class="buttonHeader">
      <div class="buttonHeader-text">{{params.displayName}}</div>
      <ng-container *ngIf="checkButtonHide(btnConfig)">

        <ng-container *ngIf="checkButtonType(btnConfig)">
          <div class="buttonHeader-icon"
               [apes-tooltip]="showTooltip(btnConfig)"
               (click)="clickButton()">
            <i apes-icon [apesType]="icon"></i>
          </div>
        </ng-container>

        <ng-container *ngIf="checkButtonType(btnConfig,'switch')">
          <!--        [apesPopoverTitle]="titleTemplate"-->
          <div class="buttonHeader-icon"
               apes-popover
               apesPopoverTrigger="click"
               [apesPopoverContent]="contentTemplate">
            <i apes-icon [apesType]="icon"></i>
          </div>
          <!--        <ng-template #titleTemplate style="width: 100px;">{{switchTitle}}</ng-template>-->
          <ng-template #contentTemplate>
            <ng-container *ngFor="let check of list; index as i;">
              <apes-switch [(ngModel)]="check.checked"
                           apesCheckedChildren="{{check.select}}"
                           apesUnCheckedChildren="{{check.unSelect}}"
                           (ngModelChange)="setNode(i, $event)"></apes-switch>
            </ng-container>
          </ng-template>
        </ng-container>

      </ng-container>
    </div>
  `,
  styles: [`
    .buttonHeader {
      display: flex;
      overflow: hidden;
      justify-content: space-between;
    }

    .buttonHeader-icon {
      cursor: pointer;
    }
  `],
})
export class ButtonHeaderComponent implements OnDestroy, IHeaderAngularComp {
  public params: MyParams;
  public showHidden: boolean = false;
  ctx: any = {};
  btnConfig: any = {};
  hide: any = '';
  callback: any;
  icon: any = 'form';

  // switch
  // switchTitle: any = '';
  list: any = [];

  private elementRef: ElementRef;
  @HostBinding('style.text-align') align: string;
  @HostBinding('style.width') width: string;

  constructor(
    elementRef: ElementRef,
    private expressionService: ExpressionService,
    private event: Events,
    protected searchService: SearchService,
  ) {
    this.elementRef = elementRef;
    this.align = 'left';
    this.width = '100%';
  }

  agInit(params: MyParams): void {
    this.params = params;
    this.ctx = this.params.context;
    if (this.params.hasOwnProperty('colDef')) {
      this.btnConfig = getO(this.params['colDef'].buttonHeader);
      this.callback = this.params['colDef'].callback;
    } else {
      this.btnConfig = getO(this.params.column['colDef'].buttonHeader);
      this.callback = this.params.column['colDef'].callback;
    }
    if (this.btnConfig.hasOwnProperty('icon')) {
      this.icon = this.btnConfig.icon;
    }
    this.initData();
  }

  ngOnDestroy() {
  }

  initData() {
    let btn;
    if (this.btnConfig.action == 'switch') {
      btn = this.btnConfig;
      this.list = deepClone(btn.list);
      this.params.column['filterActive'] = true;
      // this.switchTitle = btn.title;


      this.list.forEach((item) => {
        if (item.hasOwnProperty('init')) {
          item.checked = this.expressionService.eval(item['init'], {
            context: this.ctx,
            model: this.ctx['model'],
          });
        }
      });
    }
  }

  checkButtonHide(btn) {
    if (!btn) return true;
    let expression = btn.hasOwnProperty('hide') ? btn['hide'] : 'false';
    return !this.expressionService.eval(expression, {
      context: this.ctx,
      model: this.ctx['model'],
    });
  }

  checkButtonType(con, type?) {
    if (!con) return;
    let check = ['dialog'];
    let show = false;
    if (type) {
      show = con.action == type;
    } else {
      check.forEach((c) => {
        if (c == con.action) {
          show = true;
        }
      });
    }
    return show;
  }

  clickButton() {
    let check = !this.checkDisabled();
    if (check) {
      let action = this.btnConfig['action'];
      if (action == 'dialog') {
        this.openDialog(this.btnConfig);
      }
    }
  }

  checkDisabled() {
    let expression = this.btnConfig['disabled'] ? this.btnConfig['disabled'] : 'false';
    return this.expressionService.eval(expression, {
      ctx: this.ctx,
      model: this.ctx['model'],
    });
  }

  openDialog(params) {
    let formId = '';
    let multiple = params.rowSelection === 'multiple' || false;
    let dialog;

    let gridData = '';
    let conditionModel = {};
    let gridName = this.ctx['gridName'];
    if (this.ctx.hasOwnProperty('model')) {
      conditionModel = { ...this.ctx['model'] };
      gridData = this.ctx['model'][gridName];
    }
    const options = {
      multiple: multiple,
      ...params,
      conditionModel: conditionModel,
      gridData: gridData,
    };

    if (params.hasOwnProperty('formId')) {
      formId = params.formId;
    } else {
      formId = params.api;
    }

    if (params.hasOwnProperty('width')) {
      options['width'] = params.width;
    }

    // 用于判断是否新增行或更新表内数据
    if (params.compile) {
      dialog = ApesInputFormComponent;
    }

    this.searchService.openDialog(formId, options, (result: any) => {
      let callbackBody = this.callback;

      if (result && (result.length > 0 || typeof result == 'object')) {
        let data = {
          data: result,
          multiple: multiple,
        };

        this.expressionService.evaluate(callbackBody, {
          context: this.ctx,
          form: this.ctx['form'],
          model: this.ctx['model'],
          data: data,
          value: result,
          event: this.event,
        }, true);
      }
    }, dialog).subscribe();
  }

  setNode(i, param) {
    let trigger = null;
    if (this.list[i].trigger) {
      trigger = this.expressionService.evaluate(this.list[i].trigger, {
        form: this.ctx['form'],
        context: this.ctx,
        model: this.ctx['model'],
        value: param,
      }, true);
    }
  }

  showTooltip(param) {
    let tooltipFormatter = param.tooltipFormatter;
    if (tooltipFormatter) {
      return this.expressionService.evaluate(tooltipFormatter, {
        context: this.ctx,
        form: this.ctx['form'],
        model: this.ctx['model'],
        event: this.event,
      });
    } else {
      return null;
    }
  }


  refresh(params): boolean {
    return true;
  }
}
